<template>
  <div class="app-container">
    <!-- 标签页 -->
    <el-tabs v-model="activeTab" @tab-click="handleTabClick">
      <!-- 待配单标签页 -->
      <el-tab-pane label="待配单" name="pending">
        <el-card>
          <div slot="header" class="clearfix">
            <span>待配单列表</span>
          </div>
          <el-table v-loading="loading" :data="pendingList" style="width: 100%">
            <el-table-column label="单据类型" align="center" prop="documentType">
              <template slot-scope="scope">
                <el-tag v-if="scope.row.documentType === 'declaration'">报关单</el-tag>
                <el-tag v-else-if="scope.row.documentType === 'invoice'">发票</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="单据编号" align="center" prop="documentNo" />
            <el-table-column label="金额" align="center" prop="amount" />
            <el-table-column label="创建时间" align="center" prop="createTime" width="180" />
          </el-table>
        </el-card>
      </el-tab-pane>

      <!-- 已配单标签页 -->
      <el-tab-pane label="已配单" name="matched">
        <el-card>
          <div slot="header" class="clearfix">
            <span>已配单列表</span>
            <el-button
              style="float: right; margin-left: 10px;"
              type="primary"
              size="mini"
              icon="el-icon-refresh"
              @click="refreshMatchedList"
              v-hasPermi="['fiscale:refund:matching:refresh']"
            >刷新</el-button>
          </div>
          
          <!-- 筛选条件 -->
          <el-form :model="matchedQueryParams" ref="matchedQueryForm" :inline="true" label-width="68px">
            <el-form-item label="匹配方式" prop="matchingType">
              <el-select v-model="matchedQueryParams.matchingType" placeholder="请选择匹配方式" clearable size="small">
                <el-option label="自动匹配" value="auto" />
                <el-option label="手动匹配" value="manual" />
              </el-select>
            </el-form-item>
            <el-form-item label="日期范围">
              <el-date-picker
                v-model="dateRange"
                size="small"
                style="width: 240px"
                value-format="yyyy-MM-dd"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              ></el-date-picker>
            </el-form-item>
            <el-form-item label="报关单号" prop="declarationNo">
              <el-input
                v-model="matchedQueryParams.declarationNo"
                placeholder="请输入报关单号"
                clearable
                size="small"
                @keyup.enter.native="handleMatchedQuery"
              />
            </el-form-item>
            <el-form-item label="发票号" prop="invoiceNo">
              <el-input
                v-model="matchedQueryParams.invoiceNo"
                placeholder="请输入发票号"
                clearable
                size="small"
                @keyup.enter.native="handleMatchedQuery"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleMatchedQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetMatchedQuery">重置</el-button>
            </el-form-item>
          </el-form>

          <!-- 已配单表格 -->
          <el-table v-loading="loading" :data="matchedList" @selection-change="handleMatchedSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="报关单号" align="center" prop="declarationNo" />
            <el-table-column label="发票号" align="center" prop="invoiceNo" />
            <el-table-column label="匹配方式" align="center" prop="matchingType">
              <template slot-scope="scope">
                <el-tag v-if="scope.row.matchingType === 'auto'" type="success">自动</el-tag>
                <el-tag v-else-if="scope.row.matchingType === 'manual'" type="warning">手动</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="匹配时间" align="center" prop="matchingTime" width="180" />
            <el-table-column label="操作人" align="center" prop="operator" />
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-refresh-left"
                  @click="handleCancelMatching(scope.row)"
                  v-if="scope.row.matchingType === 'manual'"
                  v-hasPermi="['fiscale:refund:matching:cancel']"
                >取消配对</el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <pagination
            v-show="matchedTotal > 0"
            :total="matchedTotal"
            :page.sync="matchedQueryParams.pageNum"
            :limit.sync="matchedQueryParams.pageSize"
            @pagination="getMatchedList"
          />
        </el-card>
      </el-tab-pane>

      <!-- 配单异常标签页 -->
      <el-tab-pane label="配单异常" name="exception">
        <el-card>
          <div slot="header" class="clearfix">
            <span>配单异常</span>
            <el-button
              style="float: right;"
              type="primary"
              size="mini"
              icon="el-icon-refresh"
              @click="refreshExceptionList"
              v-hasPermi="['fiscale:refund:matching:refresh']"
            >刷新</el-button>
          </div>
          
          <el-row :gutter="20">
            <!-- 左侧：未匹配报关单列表 -->
            <el-col :span="12">
              <el-card>
                <div slot="header" class="clearfix">
                  <span>未匹配报关单</span>
                </div>
                <el-table 
                  v-loading="declarationLoading" 
                  :data="declarationList" 
                  @selection-change="handleDeclarationSelectionChange"
                  highlight-current-row
                  @current-change="handleDeclarationCurrentChange"
                >
                  <el-table-column type="selection" width="55" align="center" />
                  <el-table-column label="报关单号" align="center" prop="declarationNo" />
                  <el-table-column label="金额" align="center" prop="totalAmount" />
                  <el-table-column label="日期" align="center" prop="exportDate" width="100" />
                  <el-table-column label="商品摘要" align="center" prop="productSummary" />
                  <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                    <template slot-scope="scope">
                      <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-magic-stick"
                        @click="handleRecommend(scope.row)"
                        v-hasPermi="['fiscale:refund:matching:recommend']"
                      >智能推荐</el-button>
                    </template>
                  </el-table-column>
                </el-table>
                
                <!-- 报关单分页 -->
                <pagination
                  v-show="declarationTotal > 0"
                  :total="declarationTotal"
                  :page.sync="declarationQueryParams.pageNum"
                  :limit.sync="declarationQueryParams.pageSize"
                  @pagination="getUnmatchedDeclarations"
                />
              </el-card>
            </el-col>

            <!-- 右侧：未匹配发票列表 -->
            <el-col :span="12">
              <el-card>
                <div slot="header" class="clearfix">
                  <span>未匹配发票</span>
                </div>
                <el-table 
                  v-loading="invoiceLoading" 
                  :data="invoiceList" 
                  @selection-change="handleInvoiceSelectionChange"
                  highlight-current-row
                  @current-change="handleInvoiceCurrentChange"
                >
                  <el-table-column type="selection" width="55" align="center" />
                  <el-table-column label="发票号" align="center" prop="invoiceNo" />
                  <el-table-column label="金额" align="center" prop="totalAmount" />
                  <el-table-column label="日期" align="center" prop="createTime" width="100" />
                  <el-table-column label="商品摘要" align="center" prop="productSummary" />
                </el-table>
                
                <!-- 发票分页 -->
                <pagination
                  v-show="invoiceTotal > 0"
                  :total="invoiceTotal"
                  :page.sync="invoiceQueryParams.pageNum"
                  :limit.sync="invoiceQueryParams.pageSize"
                  @pagination="getUnmatchedInvoices"
                />
              </el-card>
            </el-col>
          </el-row>

          <!-- 核心操作区 -->
          <el-card style="margin-top: 20px;">
            <div slot="header" class="clearfix">
              <span>核心操作</span>
            </div>
            <el-row :gutter="20" type="flex" justify="center">
              <el-col :span="6" style="text-align: center;">
                <el-button
                  type="primary"
                  icon="el-icon-link"
                  size="medium"
                  @click="handleManualLink"
                  :disabled="!selectedDeclaration || !selectedInvoice"
                  v-hasPermi="['fiscale:refund:matching:manual']"
                >手动关联</el-button>
              </el-col>
              <el-col :span="6" style="text-align: center;">
                <el-button
                  type="danger"
                  icon="el-icon-warning"
                  size="medium"
                  @click="handleMarkException"
                  :disabled="!selectedDeclaration && !selectedInvoice"
                  v-hasPermi="['fiscale:refund:matching:exception']"
                >标记为异常</el-button>
              </el-col>
            </el-row>
          </el-card>
        </el-card>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import { listPendingMatching, listMatched, listExceptions, cancelMatching, recommendMatching, manualMatching, markException, listUnmatchedDeclarations, listUnmatchedInvoices } from "@/api/fiscale/refund";

export default {
  name: "MatchingEngine",
  data() {
    return {
      // 活动标签页
      activeTab: "pending",
      
      // 加载状态
      loading: true,
      declarationLoading: false,
      invoiceLoading: false,
      
      // 待配单数据
      pendingList: [],
      
      // 已配单数据
      matchedList: [],
      matchedTotal: 0,
      matchedQueryParams: {
        pageNum: 1,
        pageSize: 10,
        matchingType: null,
        declarationNo: null,
        invoiceNo: null
      },
      dateRange: [],
      matchedSelection: [],
      
      // 配单异常数据
      declarationList: [],
      invoiceList: [],
      selectedDeclaration: null,
      selectedInvoice: null,
      
      // 报关单分页参数
      declarationTotal: 0,
      declarationQueryParams: {
        pageNum: 1,
        pageSize: 10
      },
      
      // 发票分页参数
      invoiceTotal: 0,
      invoiceQueryParams: {
        pageNum: 1,
        pageSize: 10
      },
      
      // 异常数据
      exceptionList: []
    };
  },
  created() {
    this.getPendingList();
  },
  methods: {
    /** 标签页切换 */
    handleTabClick(tab) {
      if (tab.name === "pending") {
        this.getPendingList();
      } else if (tab.name === "matched") {
        this.getMatchedList();
      } else if (tab.name === "exception") {
        this.getExceptionList();
      }
    },
    
    /** 获取待配单列表 */
    getPendingList() {
      this.loading = true;
      listPendingMatching().then(response => {
        this.pendingList = response.rows;
        this.loading = false;
      }).catch(() => {
        // 如果API调用失败，使用模拟数据
        this.pendingList = [
          {
            documentType: "declaration",
            documentNo: "BG20250920001",
            amount: "10000.00",
            createTime: "2025-09-20"
          },
          {
            documentType: "invoice",
            documentNo: "FP20250920001",
            amount: "10000.00",
            createTime: "2025-09-20"
          }
        ];
        this.loading = false;
      });
    },
    
    /** 获取已配单列表 */
    getMatchedList() {
      this.loading = true;
      listMatched(this.matchedQueryParams).then(response => {
        this.matchedList = response.rows;
        this.matchedTotal = response.total;
        this.loading = false;
      });
    },
    
    /** 获取配单异常列表 */
    getExceptionList() {
      this.loading = true;
      listExceptions({}).then(response => {
        this.exceptionList = response.rows;
        this.loading = false;
      });
      
      // 获取未匹配的报关单和发票列表
      this.getUnmatchedDeclarations();
      this.getUnmatchedInvoices();
    },
    
    /** 获取未匹配的报关单列表 */
    getUnmatchedDeclarations() {
      this.declarationLoading = true;
      listUnmatchedDeclarations(this.declarationQueryParams).then(response => {
        this.declarationList = response.rows;
        this.declarationTotal = response.total;
        this.declarationLoading = false;
      }).catch(() => {
        this.declarationLoading = false;
      });
    },
    
    /** 获取未匹配的发票列表 */
    getUnmatchedInvoices() {
      this.invoiceLoading = true;
      listUnmatchedInvoices(this.invoiceQueryParams).then(response => {
        this.invoiceList = response.rows;
        this.invoiceTotal = response.total;
        this.invoiceLoading = false;
      }).catch(() => {
        this.invoiceLoading = false;
      });
    },
    
    /** 刷新已配单列表 */
    refreshMatchedList() {
      this.getMatchedList();
      this.$message.success("刷新成功");
    },
    
    /** 刷新异常列表 */
    refreshExceptionList() {
      this.getExceptionList();
      this.$message.success("刷新成功");
    },
    
    /** 已配单搜索 */
    handleMatchedQuery() {
      this.matchedQueryParams.pageNum = 1;
      this.getMatchedList();
    },
    
    /** 重置已配单搜索 */
    resetMatchedQuery() {
      this.dateRange = [];
      this.resetForm("matchedQueryForm");
      this.handleMatchedQuery();
    },
    
    /** 已配单多选 */
    handleMatchedSelectionChange(selection) {
      this.matchedSelection = selection;
    },
    
    /** 报关单选择变化 */
    handleDeclarationSelectionChange(selection) {
      // 只允许选择一个
      if (selection.length > 0) {
        this.selectedDeclaration = selection[0];
      } else {
        this.selectedDeclaration = null;
      }
    },

    /** 报关单当前行变化 */
    handleDeclarationCurrentChange(currentRow) {
      this.selectedDeclaration = currentRow;
    },

    /** 发票选择变化 */
    handleInvoiceSelectionChange(selection) {
      // 只允许选择一个
      if (selection.length > 0) {
        this.selectedInvoice = selection[0];
      } else {
        this.selectedInvoice = null;
      }
    },

    /** 发票当前行变化 */
    handleInvoiceCurrentChange(currentRow) {
      this.selectedInvoice = currentRow;
    },

    /** 智能推荐 */
    handleRecommend(row) {
      recommendMatching(row.declarationId).then(response => {
        this.$message.success("智能推荐成功");
        // 这里应该高亮显示推荐的发票
        // 可以在界面中显示推荐结果
        if (response.data && response.data.length > 0) {
          // 示例：显示推荐的发票信息
          let message = "推荐的发票：";
          response.data.forEach(item => {
            message += item.invoice.invoiceNo + " ";
          });
          this.$message.info(message);
        } else {
          this.$message.info("未找到匹配的发票");
        }
      });
    },

    /** 手动关联 */
    handleManualLink() {
      this.$prompt('请输入匹配原因', '手动关联', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^.{1,100}$/,
        inputErrorMessage: '匹配原因长度应在1-100个字符之间'
      }).then(({ value }) => {
        const request = {
          declarationId: this.selectedDeclaration.declarationId,
          invoiceId: this.selectedInvoice.invoiceId,
          matchReason: value
        };
        return manualMatching(request);
      }).then(() => {
        this.getExceptionList();
        this.$message.success("手动关联成功");
      }).catch(() => {});
    },

    /** 标记为异常 */
    handleMarkException() {
      this.$prompt('请输入异常原因', '标记为异常', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^.{1,50}$/,
        inputErrorMessage: '异常原因长度应在1-50个字符之间'
      }).then(({ value }) => {
        let request = {
          exceptionReason: value,
          remark: ""
        };

        if (this.selectedDeclaration) {
          request.documentType = "declaration";
          request.documentId = this.selectedDeclaration.declarationId;
        } else if (this.selectedInvoice) {
          request.documentType = "invoice";
          request.documentId = this.selectedInvoice.invoiceId;
        }

        return markException(request);
      }).then(() => {
        this.getExceptionList();
        this.$message.success("标记异常成功");
      }).catch(() => {});
    }
  }
};
</script>

<style scoped>
.el-card {
  margin-bottom: 20px;
}
</style>